# coding:utf-8
class Admin::TrafficStrategiesController < AdminController
	
  respond_to :html, :json

  before_filter :check_access
  set_tab :business
  before_filter :setup, only: [:index]

  def index

    if params[:terminal_group_id].present?
      @terminal_group = TerminalGroup.where(id: params[:terminal_group_id]).first 
      @city = @terminal_group.city if @terminal_group
      @traffic_strategies = TrafficStrategy.by_terminal_group(params[:terminal_group_id])
    end

    if params[:city_id].present?
      @city = City.where(id: params[:city_id]).first
      @traffic_strategies = TrafficStrategy.by_city(params[:city_id])
    end

    @ways = ["业务","用户分组管理",@city.province.name,@city.name]
    @ways << @terminal_group.group_name if @terminal_group
    @ways << "策略管理"
    
    eval %{ set_tab :traffic_strategy_city_#{@city.id}, :sub_nav }

    @traffic_strategies = @traffic_strategies.order('id ASC').page(params[:page])

	end

  def new
    @traffic_strategy = TrafficStrategy.new(terminal_group_id: params[:terminal_group_id])
  end

  def edit
    @traffic_strategy = TrafficStrategy.find params[:id]
  end

  def create
    @traffic_strategy = TrafficStrategy.new(params[:traffic_strategy])
    if params[:promotion_info]
      render :action => :new unless @traffic_strategy.cover_using_strategy
    else
      render :action => :new unless @traffic_strategy.save
    end
  end

  def update
    @traffic_strategy = TrafficStrategy.find params[:id]
    if params[:promotion_info]
      render :action => :edit unless @traffic_strategy.assign_attributes_from_params(params[:traffic_strategy]) && @traffic_strategy.cover_using_strategy
    else
      render :action => :edit unless @traffic_strategy.update_attributes(params[:traffic_strategy])
    end
  end

  def destroy
    @traffic_strategy = TrafficStrategy.find params[:id]
    @traffic_strategy.destroy
  end

  def enforce
    Creditcard.delete_all
  end

  private

  def setup
    @left_panel = "layouts/account_widget"
  end

  def check_access
    if params[:city_id].present?
      @city = City.find_by_id(params[:city_id])
      unless current_admin.can_access?(@city)
        render :file => "public/403.html", :status => 403
      end
    end
  end

end